package com.weishi.project.training.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.api.controller.selection.WeekPlanMethod;
import com.weishi.project.api.dto.DynamometerRankingDTO;
import com.weishi.project.api.vo.DynamometerRankingListVO;
import com.weishi.project.api.vo.HandUpCgyBean;
import com.weishi.project.api.vo.appvo.SubsectionDTO;
import com.weishi.project.sport.movement.vo.TrainingReportBean;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.mapper.DynamometerMapper;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.AccessControlException;
import java.util.*;

import static com.weishi.common.utils.StringUtils.turnSecond;

/**
 * 测功仪数据Service业务层处理
 */
@Service
public class DynamometerServiceImpl extends ServiceImpl<DynamometerMapper, Dynamometer> implements IDynamometerService {


    @Resource
    private DynamometerMapper dynamometerMapper;

    /**
     * 测功仪成绩排名 接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    /**
     * 运动员接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 训练成绩 接口
     */
    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    @Autowired
    private ITrainingGroupService trainingGroupService;

    /**
     * 测功仪分段 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;

    /**
     * 运动员成绩
     */
    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    /**
     * 训练课接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    /**
     * redis 数据库
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IDynamometerService dynamometerService;


    /**
     * 查询测功仪数据列表
     */
    @Override
    public List<Dynamometer> selectDynamometerList(Dynamometer dynamometer) {
        return dynamometerMapper.selectDynamometerList(dynamometer);
    }


    /**
     * 查询测功仪平均心率
     */
    @Override
    public Integer getAverageHeartRate(Integer userId, Integer trainingDayId, Integer trainingMode, Integer groupId) {
        return dynamometerMapper.getAverageHeartRate(userId , trainingDayId , trainingMode , groupId);
    }


    /**
     * 教练员端 -- 查询测功仪男女最新排名
     */
    @Override
    public AjaxResult getDynamometerRanking(DynamometerRankingDTO dynamometerRankingDTO) {
        DynamometerRankingListVO dynamometerRankingListVO = new DynamometerRankingListVO();
        List<DynamometerRanking> dynamometerList = new ArrayList<>();
        List<DynamometerRanking> dynamometerList2 = new ArrayList<>();

        //判断时间还是公里数 0 是公里数 1 是时间
        if (dynamometerRankingDTO.getTrainingMode() == 0) {
            // 男性排名成绩
            Long groupId = Long.parseLong(dynamometerRankingDTO.getGroupId().toString());
            List<DynamometerRanking> dynamometerRankings = redisTemplate.boundHashOps("dynamometerRanking" + groupId.toString()).values();
            if (dynamometerRankings.size() > 0) {
                //  0 代表 男   1 代表 女
                if (dynamometerRankings.size() > 0) dynamometerRankings.forEach(p -> {
                    // 设置保留 1 位小数
                    p.setPropellerFrequency(StringUtils.numberDigits(Double.parseDouble(p.getPropellerFrequency()) , 1).toString());
                    if (p.getSex() == 0) {
                        dynamometerList.add(p);
                    } else {
                        dynamometerList2.add(p);
                    }
                });
            }
            // 男性排名成绩
            List<DynamometerRanking> dynamometerList3 = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getGroupId, dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex, 0).orderByAsc(DynamometerRanking::getLengthTime));
            if(dynamometerList3.size() > 0)dynamometerList3.forEach( p-> {
                // 设置保留 1 位小数
                p.setPropellerFrequency(StringUtils.numberDigits(Double.parseDouble(p.getPropellerFrequency()) , 1).toString());
                dynamometerList.add(p);
            });
            //使用Collections集合工具类进行排序
            Collections.sort(dynamometerList, new Comparator<DynamometerRanking>() {
                @Override
                public int compare(DynamometerRanking o1, DynamometerRanking o2) {
                    //升序排序，降序反写
                    return Integer.parseInt(String.valueOf(o1.getTimeMillisecond())) - Integer.parseInt(String.valueOf(o2.getTimeMillisecond()));
                }
            });
            dynamometerRankingListVO.setRankingMale(dynamometerList);

            // 女性排名成绩
            List<DynamometerRanking> dynamometerList4 = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getGroupId, dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex, 1).orderByDesc(DynamometerRanking::getMileage));
            if(dynamometerList4.size() > 0)dynamometerList4.forEach( p-> {
                // 设置保留 1 位小数
                p.setPropellerFrequency(StringUtils.numberDigits(Double.parseDouble(p.getPropellerFrequency()) , 1).toString());
                dynamometerList2.add(p);
            });
            //使用Collections集合工具类进行排序
            Collections.sort(dynamometerList2, new Comparator<DynamometerRanking>() {
                @Override
                public int compare(DynamometerRanking o1, DynamometerRanking o2) {
                    //升序排序，降序反写
                    return Integer.parseInt(String.valueOf(o1.getTimeMillisecond())) - Integer.parseInt(String.valueOf(o2.getTimeMillisecond()));
                }
            });
            dynamometerRankingListVO.setRankingFemale(dynamometerList2);
            return AjaxResult.success(dynamometerRankingListVO);

        }else{
            // 时间手段训练
            // 男性排名成绩
            Long groupId = Long.parseLong(dynamometerRankingDTO.getGroupId().toString());
            List<DynamometerRanking> dynamometerRankings = redisTemplate.boundHashOps("dynamometerRanking" + groupId.toString()).values();
            if(dynamometerRankings.size() > 0){
                //  0 代表 男   1 代表 女
                if(dynamometerRankings.size() > 0)dynamometerRankings.forEach( p-> {
                    // 设置保留 1 位小数
                    p.setPropellerFrequency(StringUtils.numberDigits(Double.parseDouble(p.getPropellerFrequency()) , 1).toString());
                    if(p.getSex() == 0){
                        System.out.println();
                        dynamometerList.add(p);
                    }else{
                        dynamometerList2.add(p);
                    }
                });
            }
            // 男性排名成绩
            List<DynamometerRanking> dynamometerList3 = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getGroupId, dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex, 0).orderByDesc(DynamometerRanking::getMileage));
            if(dynamometerList3.size() > 0)dynamometerList3.forEach( p-> {
                // 设置保留 1 位小数
                p.setPropellerFrequency(StringUtils.numberDigits(Double.parseDouble(p.getPropellerFrequency()) , 1).toString());
                dynamometerList.add(p);
            });
            //使用Collections集合工具类进行排序
            Collections.sort(dynamometerList, new Comparator<DynamometerRanking>() {
                @Override
                public int compare(DynamometerRanking o1, DynamometerRanking o2) {
                    //升序排序，降序反写
                    return (int)o2.getMileage() - (int)o1.getMileage();
                }
            });
            dynamometerRankingListVO.setRankingMale(dynamometerList);

            // 女性排名成绩
            List<DynamometerRanking> dynamometerList4 = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getGroupId, dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex, 1).orderByDesc(DynamometerRanking::getMileage));
            if(dynamometerList4.size() > 0)dynamometerList4.forEach( p-> {
                // 设置保留 1 位小数
                p.setPropellerFrequency(StringUtils.numberDigits(Double.parseDouble(p.getPropellerFrequency()) , 1).toString());
                dynamometerList2.add(p);
            });
            //使用Collections集合工具类进行排序
            Collections.sort(dynamometerList2, new Comparator<DynamometerRanking>() {
                @Override
                public int compare(DynamometerRanking o1, DynamometerRanking o2) {
                    //升序排序，降序反写
                    return (int)o2.getMileage() - (int)o1.getMileage();
                }
            });
            dynamometerRankingListVO.setRankingFemale(dynamometerList2);
            return AjaxResult.success(dynamometerRankingListVO);

        }
    }



    /**
     * 教练员端 -- 手动新增运动员成绩
     */
    @Transactional
    @Override
    public AjaxResult addDynamometer(JSONObject jsonObject) {

        // 判断运动员是否已经新增过成绩，如果有就返回新增失败
        DynamometerRanking judge = dynamometerRankingService
                .getOne(Wrappers.<DynamometerRanking>lambdaQuery()
                        .eq(DynamometerRanking::getSportsmanId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))
                        .eq(DynamometerRanking::getGroupId , Integer.parseInt(jsonObject.get("groupId").toString())));
        if(StringUtils.isNotNull(judge)){
            return AjaxResult.error(206 ,"不能重复添加运动员成绩！");
        }

        int size = 0;

        // 计算分段瓦特平均值
        Integer averageWatt =0;

        // 计算分段功率平均值
        Long averagePower =0L;

        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<HandUpCgyBean> dynamometerList = JSON.parseArray(jsonArray.toString(), HandUpCgyBean.class);
        List<String> segmentedTimingList = new ArrayList<>();
        if(dynamometerList.size() > 0){
            dynamometerList.forEach( p->{
                segmentedTimingList.add(p.getLengthTime());
            });
        }

        // 总距离
        double mileage = 0.0;

        // 总时长
        Long lengthTime = 0L;

        String segmentedTiming = "";
        // 新增教练员端的成绩
        TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
        trainingGroupChannel.setBatch(0);
        trainingGroupChannel.setChannelName("0");
        trainingGroupChannel.setPower(jsonObject.get("totalpower").toString());
        for(int g = 0; g<dynamometerList.size(); g++){
            segmentedTiming += dynamometerList.get(g).getLengthTime() + " ";
            mileage += dynamometerList.get(g).getMileage();
            lengthTime += turnSecond(dynamometerList.get(g).getLengthTime());
        }
        if(Integer.parseInt(jsonObject.get("trainingMode").toString()) == 0){
            trainingGroupChannel.setAchievement(StringUtils.millisecondRotationTime(lengthTime));
            trainingGroupChannel.setRowingKilometers(Integer.parseInt(jsonObject.get("totalLength").toString()));
        }else{
            trainingGroupChannel.setAchievement(String.valueOf(mileage));
            trainingGroupChannel.setRowingKilometers(Integer.parseInt(jsonObject.get("totalLength").toString()));
        }
        trainingGroupChannel.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
        trainingGroupChannel.setCtime(new Date());
        trainingGroupChannel.setWatt("0");
        trainingGroupChannel.setSegmentedTiming(segmentedTiming.substring(0 , segmentedTiming.length()-1));
        trainingGroupChannelService.save(trainingGroupChannel);

        //同步完成公里数
        //获取小组实际公里数(第一批次，第一航道的实际划行数) [公里数维度，时间维度暂时忽略]
        if (trainingGroupChannel.getChannelName().equals("0") && trainingGroupChannel.getBatch() == 0) {
            trainingGroupChannel = trainingGroupChannelService.getById(trainingGroupChannel.getId());
            TrainingGroup trainingGroup = trainingGroupService.getById(trainingGroupChannel.getGroupId());
            if(trainingGroup.getKilometer()==0d){
                trainingGroup.setKilometer(trainingGroupChannel.getRowingKilometers());
                trainingGroupService.updateById(trainingGroup);
                //异步汇总训练项目数据
                trainingDayService.aggregateData(trainingGroup.getTrainingDayId());
            }
        }


        List<Map<String,Object>> jsondate = new ArrayList<>();
        Dynamometer dynamometer = new Dynamometer();
        for (int i = 0; i<dynamometerList.size(); i++){
            if(jsonObject.get("trainingMode").equals(0)){
                if(i == 0){
                    StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                    dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                    dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                    dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                    dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                    dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                    dynamometer.setPower(jsonObject.get("totalpower").toString());
                    dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                    dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                    dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                    dynamometer.setCtime(new Date());
                    //save(dynamometer);

                    Map<String,Object> temp = new HashMap<>();
                    temp.put("mileage" , dynamometer.getMileage());
                    temp.put("propellerFrequency" , dynamometer.getPropellerFrequency());
                    temp.put("heartRate" , dynamometer.getHeartRate() == null ? 0 : dynamometer.getHeartRate());
                    temp.put("lengthTime" , dynamometer.getLengthTime());
                    temp.put("speed" , dynamometer.getSpeed() == null ? 0.0 : dynamometer.getSpeed());
                    temp.put("power" , dynamometer.getPower());
                    temp.put("watt" , dynamometer.getWatt());
                    temp.put("peakForce" , dynamometer.getPeakForce() == null ? 0.0 : dynamometer.getPeakForce());
                    temp.put("averageForce" , dynamometer.getAverageForce() == null ? 0.0 : dynamometer.getAverageForce());
                    temp.put("pulpNumber" , dynamometer.getPulpNumber() == null ? 0 : dynamometer.getPulpNumber());
                    temp.put("trainingMode" , dynamometer.getTrainingMode() == null ? 0.0 : dynamometer.getTrainingMode());
                    temp.put("segmentNumber" , dynamometer.getSegmentNumber() == null ? 0.0 : dynamometer.getSegmentNumber());
                    jsondate.add(temp);


                    /**
                     * 添加分段成绩表数据
                     */
                    DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                    StringUtils.copyProperties(dynamometer , dynamometerSubsection);
                    dynamometerSubsection.setChannelId(trainingGroupChannel.getId());
                    dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                    int trainingMode = Integer.parseInt(jsonObject.get("trainingMode").toString());
                    if(trainingMode == 0){
                        dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                        dynamometerSubsection.setLengthTime(WeekPlanMethod.timeAdd(segmentedTimingList , size , i , trainingMode));
                        size++;
                    }else{
                        dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                        dynamometerSubsection.setLengthTime(dynamometerList.get(i).getLengthTime());
                        size++;
                    }
                    dynamometerSubsection.setSpeed(0.0);
                    dynamometerSubsection.setPower(dynamometerList.get(i).getPower());
                    dynamometerSubsection.setSegmentNumber(i+1);
                    dynamometerSubsectionService.save(dynamometerSubsection);
                }else{
                    // 计算时间
                    if(i <= dynamometerList.size()){
                        Long goUp = turnSecond(dynamometerList.get(i-1).getLengthTime());
                        Long under = turnSecond(dynamometerList.get(i).getLengthTime());
                        Long totals = goUp+under;

                        StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                        dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                        dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                        dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                        dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                        dynamometer.setLengthTime(StringUtils.millisecondRotationTime(totals));
                        dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                        dynamometer.setPower(jsonObject.get("totalpower").toString());
                        dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                        dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                        dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                        dynamometer.setCtime(new Date());
                        //save(dynamometer);

                        Map<String,Object> temp = new HashMap<>();
                        temp.put("mileage" , dynamometer.getMileage());
                        temp.put("propellerFrequency" , dynamometer.getPropellerFrequency());
                        temp.put("heartRate" , dynamometer.getHeartRate() == null ? 0 : dynamometer.getHeartRate());
                        temp.put("lengthTime" , dynamometer.getLengthTime());
                        temp.put("speed" , dynamometer.getSpeed() == null ? 0.0 : dynamometer.getSpeed());
                        temp.put("power" , dynamometer.getPower());
                        temp.put("watt" , dynamometer.getWatt());
                        temp.put("peakForce" , dynamometer.getPeakForce() == null ? 0.0 : dynamometer.getPeakForce());
                        temp.put("averageForce" , dynamometer.getAverageForce() == null ? 0.0 : dynamometer.getAverageForce());
                        temp.put("pulpNumber" , dynamometer.getPulpNumber() == null ? 0 : dynamometer.getPulpNumber());
                        temp.put("trainingMode" , dynamometer.getTrainingMode() == null ? 0.0 : dynamometer.getTrainingMode());
                        temp.put("segmentNumber" , dynamometer.getSegmentNumber() == null ? 0.0 : dynamometer.getSegmentNumber());
                        jsondate.add(temp);

                        /**
                         * 添加分段成绩表数据
                         */
                        DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                        StringUtils.copyProperties(dynamometer , dynamometerSubsection);
                        dynamometerSubsection.setChannelId(trainingGroupChannel.getId());
                        dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                        int trainingMode = Integer.parseInt(jsonObject.get("trainingMode").toString());
                        if(trainingMode == 0){
                            dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                            dynamometerSubsection.setLengthTime(WeekPlanMethod.timeAdd(segmentedTimingList , size , i , trainingMode));
                            size++;
                        }else{
                            dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                            dynamometerSubsection.setLengthTime(dynamometerList.get(i).getLengthTime());
                            size++;
                        }
                        dynamometerSubsection.setSpeed(0.0);
                        dynamometerSubsection.setPower(dynamometerList.get(i).getPower());
                        dynamometerSubsection.setSegmentNumber(i+1);
                        dynamometerSubsectionService.save(dynamometerSubsection);
                    }
                }
            }else{
                // 计算公里数
                if(i == 0){
                    System.out.println();
                    StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                    dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                    dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                    dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                    dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                    dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                    dynamometer.setPower(jsonObject.get("totalpower").toString());
                    dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                    dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                    dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                    dynamometer.setCtime(new Date());
                    //save(dynamometer);

                    Map<String,Object> temp = new HashMap<>();
                    temp.put("mileage" , dynamometer.getMileage());
                    temp.put("propellerFrequency" , dynamometer.getPropellerFrequency());
                    temp.put("heartRate" , dynamometer.getHeartRate() == null ? 0 : dynamometer.getHeartRate());
                    temp.put("lengthTime" , dynamometer.getLengthTime());
                    temp.put("speed" , dynamometer.getSpeed() == null ? 0.0 : dynamometer.getSpeed());
                    temp.put("power" , dynamometer.getPower());
                    temp.put("watt" , dynamometer.getWatt());
                    temp.put("peakForce" , dynamometer.getPeakForce() == null ? 0.0 : dynamometer.getPeakForce());
                    temp.put("averageForce" , dynamometer.getAverageForce() == null ? 0.0 : dynamometer.getAverageForce());
                    temp.put("pulpNumber" , dynamometer.getPulpNumber() == null ? 0 : dynamometer.getPulpNumber());
                    temp.put("trainingMode" , dynamometer.getTrainingMode() == null ? 0.0 : dynamometer.getTrainingMode());
                    temp.put("segmentNumber" , dynamometer.getSegmentNumber() == null ? 0.0 : dynamometer.getSegmentNumber());
                    jsondate.add(temp);

                    /**
                     * 添加分段成绩表数据
                     */
                    DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                    StringUtils.copyProperties(dynamometer , dynamometerSubsection);
                    dynamometerSubsection.setChannelId(trainingGroupChannel.getId());
                    dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                    int trainingMode = Integer.parseInt(jsonObject.get("trainingMode").toString());
                    if(trainingMode == 0){
                        dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                        dynamometerSubsection.setLengthTime(WeekPlanMethod.timeAdd(segmentedTimingList , size , i , trainingMode));
                        size++;
                    }else{
                        dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                        dynamometerSubsection.setLengthTime(dynamometerList.get(i).getLengthTime());
                        size++;
                    }
                    dynamometerSubsection.setSpeed(0.0);
                    dynamometerSubsection.setPower(dynamometerList.get(i).getPower());
                    dynamometerSubsection.setSegmentNumber(i+1);
                    dynamometerSubsectionService.save(dynamometerSubsection);
                }else{
                    if(i <= dynamometerList.size()){
                        double goUp = dynamometerList.get(i-1).getMileage();
                        double under = dynamometerList.get(i).getMileage();
                        double total = under + goUp;
                        StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                        dynamometer.setMileage(total);
                        dynamometer.setCtime(new Date());
                        dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                        dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                        dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                        dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                        dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                        dynamometer.setPower(jsonObject.get("totalpower").toString());
                        dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                        dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                        dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());

                        Map<String,Object> temp = new HashMap<>();
                        temp.put("mileage" , dynamometer.getMileage());
                        temp.put("propellerFrequency" , dynamometer.getPropellerFrequency());
                        temp.put("heartRate" , dynamometer.getHeartRate() == null ? 0 : dynamometer.getHeartRate());
                        temp.put("lengthTime" , dynamometer.getLengthTime());
                        temp.put("speed" , dynamometer.getSpeed() == null ? 0.0 : dynamometer.getSpeed());
                        temp.put("power" , dynamometer.getPower());
                        temp.put("watt" , dynamometer.getWatt());
                        temp.put("peakForce" , dynamometer.getPeakForce() == null ? 0.0 : dynamometer.getPeakForce());
                        temp.put("averageForce" , dynamometer.getAverageForce() == null ? 0.0 : dynamometer.getAverageForce());
                        temp.put("pulpNumber" , dynamometer.getPulpNumber() == null ? 0 : dynamometer.getPulpNumber());
                        temp.put("trainingMode" , dynamometer.getTrainingMode() == null ? 0.0 : dynamometer.getTrainingMode());
                        temp.put("segmentNumber" , dynamometer.getSegmentNumber() == null ? 0.0 : dynamometer.getSegmentNumber());
                        jsondate.add(temp);

                        /**
                         * 添加分段成绩表数据
                         */
                        DynamometerSubsection dynamometerSubsection = new DynamometerSubsection();
                        StringUtils.copyProperties(dynamometer , dynamometerSubsection);
                        dynamometerSubsection.setChannelId(trainingGroupChannel.getId());
                        dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                        int trainingMode = Integer.parseInt(jsonObject.get("trainingMode").toString());
                        if(trainingMode == 0){
                            dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                            dynamometerSubsection.setLengthTime(WeekPlanMethod.timeAdd(segmentedTimingList , size , i , trainingMode));
                            size++;
                        }else{
                            dynamometerSubsection.setMileage(dynamometerList.get(i).getMileage());
                            dynamometerSubsection.setLengthTime(dynamometerList.get(i).getLengthTime());
                            size++;
                        }
                        dynamometerSubsection.setSpeed(0.0);
                        dynamometerSubsection.setPower(dynamometerList.get(i).getPower());
                        dynamometerSubsection.setSegmentNumber(i+1);
                        dynamometerSubsectionService.save(dynamometerSubsection);
                    }

                }

            }
        }


            /**
             * 把历史数据放到第一个分段里面
             */
            if(dynamometerList.size() > 0){
                List<DynamometerSubsection> dynamometerSubsectionsLimit1 = dynamometerSubsectionService
                        .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                .eq(DynamometerSubsection::getSportsmanId, Integer.parseInt(jsonObject.get("sportsmanId").toString()))
                                .eq(DynamometerSubsection::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                                .orderByAsc(DynamometerSubsection::getId));
                if(dynamometerSubsectionsLimit1.size() > 0){
                    StringUtils.copyProperties(dynamometerSubsectionsLimit1.get(0) , dynamometer);
                    dynamometerSubsectionsLimit1.get(0).setJsonData(JSONArray.toJSONString(jsondate));
                    dynamometerSubsectionService.updateById(dynamometerSubsectionsLimit1.get(0));
                }
            }


        /**        * 新增运动员测功仪数据
         * 0 加时间
         * 1 加距离
         */
        DynamometerRanking dynamometerRanking = new DynamometerRanking();
        if(jsonObject.get("trainingMode").equals(0)){
            // 0 加时间
            // 新增运动员测功仪数据
            Long totals = 0L;
            for(int i = 0; i<dynamometerList.size(); i++){
                Long under = turnSecond(dynamometerList.get(i).getLengthTime());
                totals += under;

                // 循环分段瓦特
                averageWatt+=Integer.parseInt(dynamometerList.get(i).getWatt());
                // 循环分段功率
                averagePower+=turnSecond(dynamometerList.get(i).getPower());
            }
            System.out.println();
            StringUtils.copyProperties(dynamometerList.get(dynamometerList.size()-1), dynamometerRanking);
            dynamometerRanking.setCtime(new Date());
            dynamometerRanking.setSportsmanId(Long.parseLong(jsonObject.get("sportsmanId").toString()));
            dynamometerRanking.setSex(Long.parseLong(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getSex().toString()));
            dynamometerRanking.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getName());
            dynamometerRanking.setGroupId(Long.parseLong(jsonObject.get("groupId").toString()));
            dynamometerRanking.setTrainingDayId(Long.parseLong(jsonObject.get("trainingDayId").toString()));
            dynamometerRanking.setLengthTime(StringUtils.millisecondRotationTime(totals));
            dynamometerRanking.setPulpNumber(Long.parseLong(jsonObject.get("totalpulpnums").toString()));
            Integer averageWatts = averageWatt/dynamometerList.size();
            dynamometerRanking.setWatt(averageWatts.toString()); // 分段瓦特
            Long averagePowers = averagePower/dynamometerList.size();
            dynamometerRanking.setPower(StringUtils.millisecondRotationTime(averagePowers));
            dynamometerRanking.setMileage(Integer.parseInt(jsonObject.get("totalLength").toString()));
            dynamometerRanking.setTimeMillisecond(totals);
            dynamometerRankingService.save(dynamometerRanking);

            // 添加运动员成绩
            TrainingAchievement trainingAchievement = new TrainingAchievement();
            StringUtils.copyProperties(dynamometerRanking , trainingAchievement);
            trainingAchievement.setChannelId(trainingGroupChannel.getId());
            trainingAchievement.setCtime(new Date());
            // 根据 训练课 id 查询 weekId
            trainingAchievement.setWeekId(trainingDayService.getById(jsonObject.get("trainingDayId").toString()).getWeekId());
            trainingAchievement.setAchievement(StringUtils.millisecondRotationTime(totals));
            trainingAchievementService.save(trainingAchievement);

        }else{
            // 1 加距离
            // 新增运动员测功仪数据
            double totals = 0;
            for(int i = 0; i<dynamometerList.size(); i++){
                double under = dynamometerList.get(i).getMileage();
                totals += under;

                // 循环分段瓦特
                averageWatt+=Integer.parseInt(dynamometerList.get(i).getWatt());
                // 循环分段功率
                averagePower+=turnSecond(dynamometerList.get(i).getPower());
            }
            StringUtils.copyProperties(dynamometerList.get(dynamometerList.size()-1), dynamometerRanking);
            dynamometerRanking.setCtime(new Date());
            dynamometerRanking.setSportsmanId(Long.parseLong(jsonObject.get("sportsmanId").toString()));
            dynamometerRanking.setSex(Long.parseLong(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getSex().toString()));
            dynamometerRanking.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getName());
            dynamometerRanking.setGroupId(Long.parseLong(jsonObject.get("groupId").toString()));
            dynamometerRanking.setTrainingDayId(Long.parseLong(jsonObject.get("trainingDayId").toString()));
            dynamometerRanking.setMileage(totals);
            dynamometerRanking.setPulpNumber(Long.parseLong(jsonObject.get("totalpulpnums").toString()));
            Integer averageWatts = averageWatt/dynamometerList.size();
            dynamometerRanking.setWatt(averageWatts.toString()); // 分段瓦特
            Long averagePowers = averagePower/dynamometerList.size();
            dynamometerRanking.setPower(StringUtils.millisecondRotationTime(averagePowers));
            dynamometerRanking.setMileage(Integer.parseInt(jsonObject.get("totalLength").toString()));
             totals = Math.round(Math.random()*10000);
            long totalsNew = new Double(totals).longValue();
            dynamometerRanking.setTimeMillisecond(totalsNew);
            dynamometerRankingService.save(dynamometerRanking);

            // 添加运动员成绩
            TrainingAchievement trainingAchievement = new TrainingAchievement();
            StringUtils.copyProperties(dynamometerRanking , trainingAchievement);
            trainingAchievement.setChannelId(trainingGroupChannel.getId());
            trainingAchievement.setCtime(new Date());
            // 根据 训练课 id 查询 weekId
            trainingAchievement.setWeekId(trainingDayService.getById(jsonObject.get("trainingDayId").toString()).getWeekId());
            trainingAchievement.setAchievement(String.valueOf(totals));
            trainingAchievementService.save(trainingAchievement);

        }

        trainingGroupChannel = trainingGroupChannelService.getById(trainingGroupChannel.getId());
        Long LengthTime = StringUtils.turnSecond( dynamometerRanking.getLengthTime());
        trainingGroupChannel.setRowingClassHour(LengthTime.doubleValue());
        trainingGroupChannel.setId(trainingGroupChannel.getId());
        trainingGroupChannelService.updateById(trainingGroupChannel);

        return AjaxResult.success();
    }


    // 返回 处理 教练员端 -- 查询运动员测功仪实时数据
    private List<Dynamometer> getSimp(List<Dynamometer> list,int step){
        List<Dynamometer> listRet = new ArrayList<>();
        listRet.add(list.get(0));
        int index = 0;
        for (int i = 0; i<list.size(); i++){
            index+=step;
            if(index < list.size()){
                listRet.add(list.get(index));
            }else if(index == list.size()){
                listRet.add(list.get(list.size()-1));
            }
        }

        // 删除重复的 list
        List<Dynamometer> newList = new ArrayList<>();
        for (Dynamometer cd : listRet) {
            if (!newList.contains(cd)) {
                newList.add(cd);
            }
        }
        return newList;
    }

    /**
     * 教练员端 -- 查询运动员测功仪实时数据
     */
    @Override
    public AjaxResult getRealTimeData(DynamometerRankingDTO dynamometerRankingDTO) {
        List<Dynamometer> list = list(Wrappers.<Dynamometer>lambdaQuery()
                .eq(Dynamometer::getGroupId , dynamometerRankingDTO.getGroupId())
                .eq(Dynamometer::getSportsmanId , dynamometerRankingDTO.getSportsmanId()));

        List<Dynamometer> list2 = new ArrayList<>();
        if (list.size() > 0) {
                list.forEach( p-> {
                    list2.add(p);
                });
            } else {
                List<DynamometerSubsection> list3 = dynamometerSubsectionService.list(Wrappers.<DynamometerSubsection>lambdaQuery()
                        .eq(DynamometerSubsection::getGroupId , dynamometerRankingDTO.getGroupId())
                        .eq(DynamometerSubsection::getSportsmanId , dynamometerRankingDTO.getSportsmanId())
                        .orderByAsc(DynamometerSubsection::getId));
                JSONArray jsonArray1 = JSONArray.parseArray(list3.get(0).getJsonData());
                jsonArray1.forEach(p -> {
                    //JSON对象转换成Java对象
                    JSONObject userJson = JSONObject.parseObject(p.toString());
                    Dynamometer dynamometer1 = JSON.toJavaObject(userJson, Dynamometer.class);
                    list2.add(dynamometer1);
                });
        }

        Integer index;
        // 判断 list 数量 大于 1000 每 20 条 取一条 小于 1000 或 大于 500 每10 个 取一个
        // 大于 200 小于 500  每 6 条 取一条 ，小于 200 大于 100 每 4 个取一个 小于 200 每 2个 取一个
        if(list2.size() > 1000){
            index = 20;
            return AjaxResult.success(this.getSimp(list2 , index));
        }else if(list2.size() <= 1000 && list2.size() >= 500){
            index = 10;
            return AjaxResult.success(this.getSimp(list2 , index));
        }else if(list2.size() <= 500 && list2.size() >= 200){
            index = 6;
            return AjaxResult.success(this.getSimp(list2 , index));
        }else if(list2.size() <= 200 && list2.size() >= 100){
            index = 4;
            return AjaxResult.success(this.getSimp(list2 , index));
        }else if(list2.size() <= 100 && list2.size() >= 50){
            index = 2;
            return AjaxResult.success(this.getSimp(list2 , index));
        }else if(list2.size() <= 50){
            index = 1;
            return AjaxResult.success(this.getSimp(list2 , index));
        }else{
            return AjaxResult.success(new ArrayList<>());
        }
    }


    /**
     * 教练员端 -- 查询运动员测功仪最新一条数据 ，加平均心率和最大心率
     */
    @Override
    public AjaxResult getLatest(DynamometerRankingDTO dynamometerRankingDTO) {
        // 查询测功仪分段表的数据
        List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                        .eq(DynamometerSubsection::getGroupId , dynamometerRankingDTO.getGroupId())
                        .eq(DynamometerSubsection::getSportsmanId , dynamometerRankingDTO.getSportsmanId())
                        .orderByDesc(DynamometerSubsection::getHeartRate));
        // 最大心率
        Integer maxHeartRate = 0;
        if(dynamometerSubsectionList.size()>0){
            // 取出最大心率
            maxHeartRate = dynamometerSubsectionList.get(0).getHeartRate();
        }


        Double averageSpeeds = 0.0;
        Integer averageHeartRates = 0;
        Double averagePropellerFrequencys = 0.0;
        if(dynamometerSubsectionList.size() > 0){
            // 平均心率
            Integer averageHeartRate = 0;
            // 平均桨频
            Double averagePropellerFrequency = 0.0;

            for (int i = 0; i<dynamometerSubsectionList.size(); i++){
                if(StringUtils.isNotNull(dynamometerSubsectionList.get(i).getSpeed()) && dynamometerSubsectionList.get(i).getSpeed() > 0.0){
                    averageSpeeds+=dynamometerSubsectionList.get(i).getSpeed();
                }
                averageHeartRate+=dynamometerSubsectionList.get(i).getHeartRate();
                averagePropellerFrequency+=Double.parseDouble(dynamometerSubsectionList.get(i).getPropellerFrequency());
            }
            // 计算的平均心率结果
            averageHeartRates = averageHeartRate/dynamometerSubsectionList.size();
            averagePropellerFrequencys = averagePropellerFrequency/dynamometerSubsectionList.size();
        }


        // 判断是否有值
        if(dynamometerSubsectionList.size() == 0){
            return AjaxResult.success();
        }else{

            // 查询运动员成绩信息
            DynamometerRanking dynamometerRanking = dynamometerRankingService
                    .getOne(Wrappers.<DynamometerRanking>lambdaQuery()
                            .eq(DynamometerRanking::getGroupId , dynamometerRankingDTO.getGroupId())
                            .eq(DynamometerRanking::getSportsmanId , dynamometerRankingDTO.getSportsmanId()));

            if(StringUtils.isNotNull(dynamometerRanking)){
                // 返回数据

                // 计算平均瓦特
                Integer averageWatt = 0;
                for (int i =0; i<dynamometerSubsectionList.size(); i++){
                    averageWatt+=Integer.parseInt(dynamometerSubsectionList.get(i).getWatt());
                }

                // 计算平均功率
                Long averagePower = 0L;
                for (int i =0; i<dynamometerSubsectionList.size(); i++){
                    averagePower+=turnSecond(dynamometerSubsectionList.get(i).getPower());
                }
                Dynamometer dynamometer = new Dynamometer();
                StringUtils.copyProperties(dynamometerRanking , dynamometer);
                dynamometer.setPropellerFrequency(dynamometerRanking.getPropellerFrequency());
                dynamometer.setAverageHeartRate(averageHeartRates); // 平均心率
                dynamometer.setMaxHeartRate(maxHeartRate); // 最大心率
                dynamometer.setAveragePropellerFrequency(StringUtils.numberDigits(Double.parseDouble(averagePropellerFrequencys.toString()) , 1).toString()); // 平均桨频
                dynamometer.setSpeed(averageSpeeds/dynamometerSubsectionList.size()); // 速度
                Long averagePowers = averagePower/dynamometerSubsectionList.size();
                // 计算平均功率
                dynamometer.setAveragePower(StringUtils.millisecondRotationTime(averagePowers));
                // 计算平均瓦特
                if(averageWatt>0){
                    Integer averageWatts = averageWatt/dynamometerSubsectionList.size();
                    dynamometer.setAverageWatt(averageWatts.toString()); // 平均瓦特
                }
                dynamometer.setAverageSpeed(averageSpeeds/dynamometerSubsectionList.size()); // 平均速度

                // 计算平均峰力
                Double averagePeakForce = 0.0;
                for (int i =0; i<dynamometerSubsectionList.size(); i++){
                    averagePeakForce+=dynamometerSubsectionList.get(i).getPeakForce();
                }
                //平均峰力
                if(averagePeakForce>0.0){
                    dynamometer.setAveragePeakForce(averagePeakForce/dynamometerSubsectionList.size());
                }

                // 计算平均均力
                Double averageForce = 0.0;
                for (int i =0; i<dynamometerSubsectionList.size(); i++){
                    averageForce+=dynamometerSubsectionList.get(i).getPeakForce();
                }
                if(averageForce>0.0){
                    dynamometer.setAverageForces(averageForce/dynamometerSubsectionList.size());
                }

                // 重新赋值总距离
                int zong = (int)dynamometerRanking.getMileage();
                Integer zongs = zong;
                dynamometer.setMileage(Double.parseDouble(zongs.toString()));
                // 判断桨数 如果是 null 就赋值为 0
                if(StringUtils.isNull(dynamometer.getPulpNumber())){
                    dynamometer.setPulpNumber(0);
                }

                if(StringUtils.isNotNull(dynamometerRanking.getPeakForce())){
                    dynamometer.setAveragePeakForce(dynamometerRanking.getPeakForce().doubleValue());
                }
                if(StringUtils.isNotNull(dynamometerRanking.getAverageForce())){
                    dynamometer.setAverageForces(dynamometerRanking.getAverageForce().doubleValue());
                }
                return AjaxResult.success(Optional.ofNullable(dynamometer));
            }

        }
        return null;
    }



    /**
     * 根据时间查询重复数据
     */
    @Override
    public List<Integer> getRepetitionList() {
        return dynamometerMapper.getRepetitionList();
    }



    /**
     * 查询 3 天前的数据
     */
    @Override
    public List<Integer> getThreeDayFrontList() {
        return dynamometerMapper.getThreeDayFrontList();
    }







}